package org.karelun.gef.commands;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.gef.ui.actions.Clipboard;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.karelun.gef.model.DiagramModel;
import org.karelun.gef.model.Node;
import org.karelun.gef.parts.NodePart;

public class CutNodeCommand extends AbstractCommand{
	
	private List<Node> cutList=null;
	
	private DiagramModel diagram;
	
	@SuppressWarnings("unchecked")
	public CutNodeCommand(ISelection selection){
		if(selection instanceof IStructuredSelection){
			IStructuredSelection s=(IStructuredSelection)selection;
			Iterator itera = s.iterator();
			while(itera.hasNext()){
				Object next = itera.next();
				if(next instanceof NodePart){
					Node node=(Node)((NodePart)next).getModel();
					addCopyList(node);
				}
			}
		}
	}

	private void addCopyList(Node node) {
		if(cutList==null)
			cutList=new ArrayList<Node>();
		if(cutList.contains(node))
			return;
		if(diagram==null)
			diagram=node.getDiagram();
		
		cutList.add(node);
	}

	public boolean canExecute() {
		if(cutList==null||cutList.isEmpty())
			return false;
		return true;
	}
	
	public void execute() {
		if(!canExecute())
			return;
		Clipboard.getDefault().setContents(cutList);
		
		for(Node node:cutList)
			diagram.removeNode(node);
	}
	
	public void undo() {
		for(Node node:cutList)
			diagram.addNode(node);
	}

	@Override
	public void redo() {
		execute();
	}
}
